package org.ns.summer.core;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;

public class ResourceUtils {

    public static File getPackageFile(Class<?> type) throws FileNotFoundException {
        String path = type.getPackage().getName().replace(".", File.separator);
        return getClassPathFile(path);
    }

    public static String getClasspath() {
        return getClasspath(ResourceUtils.class);
    }
    public static String getClasspath(Class<?> type) {
        String path = type.getPackage().getName().replace(".", File.separator);
        String abs = type.getClassLoader().getResource(path).toString();
        abs = abs.substring(0, abs.lastIndexOf(File.separator,abs.length() - path.length()));

        return URLDecoder.decode(abs);
    }

    public static String getClasspathRoot(Class<?> type) {
        String abs = getClasspath(type);
        if (abs.startsWith("jar:")) {
            int index = abs.indexOf(".jar");
            if (index != -1) {
                int prevIndex = abs.lastIndexOf(File.separator, index);
                if (prevIndex != -1) {
                    abs = abs.substring("jar:".length(), prevIndex);
                }
            }
        }
        return abs;
    }


    public static File getClassPathFile(String resourceLocation) throws FileNotFoundException {

        URL url = ResourceUtils.class.getClassLoader().getResource(resourceLocation);

        File file = new File(URLDecoder.decode(url.getFile()));
        if (file == null || !file.exists()) {
            throw new FileNotFoundException("文件不存在" + resourceLocation);
        }
        return file;
    }

    public static InputStream getInputStream(ClassLoader classLoader, String filePath) {
        return classLoader.getResourceAsStream(filePath);
    }
}
